import cv2
import numpy as np
def auto_canny(image, sigma=0.33):
    # 计算图像的中位数
    v = np.median(image)
    # 使用中位数计算上下阈值
    lower = int(max(0, (1.0 - sigma) * v))
    upper = int(min(255, (1.0 + sigma) * v))
    # 应用Canny边缘检测
    edged = cv2.Canny(image, lower, upper)
    return edged
# 读取图像并转换为灰度图
image = cv2.imread('chair.bmp')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 应用高斯模糊减少噪声
blurred = cv2.GaussianBlur(gray, (9, 9), 0)
# 自动Canny边缘检测
edges = auto_canny(blurred)
# 定义回调函数用于调整霍夫变换的参数
def hough_lines_params(val):
    threshold = cv2.getTrackbarPos('Threshold', 'Edges')
    min_line_length = cv2.getTrackbarPos('Min Line Length', 'Edges')
    max_line_gap = cv2.getTrackbarPos('Max Line Gap', 'Edges')

    lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold, minLineLength=min_line_length, maxLineGap=max_line_gap)

    # 创建一幅空白图像来画线
    lines_image = np.zeros_like(image)

    if lines is not None:
        for line in lines:
            x1, y1, x2, y2 = line[0]
            cv2.line(lines_image, (x1, y1), (x2, y2), (0, 0, 255), 2)

    # 将原始图像和线条图像合并
    result = cv2.addWeighted(image, 0.8, lines_image, 1, 0)
    cv2.imshow("Edges", result)

# 创建窗口和轨迹条
cv2.namedWindow('Edges')
cv2.createTrackbar('Threshold', 'Edges', 50, 255, hough_lines_params)
cv2.createTrackbar('Min Line Length', 'Edges', 10, 200, hough_lines_params)
cv2.createTrackbar('Max Line Gap', 'Edges', 10, 50, hough_lines_params)

# 显示初始结果
cv2.imshow('Edges', edges)
cv2.waitKey(0)
cv2.destroyAllWindows()